package com.jbp.service;

import com.alibaba.fastjson.JSON;
import com.jbp.exception.RRException;
import com.jbp.model.LoginParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;


@Service
public class QqLoginUtil {

    private static final Logger logger = LoggerFactory.getLogger(QqLoginUtil.class);

    @Autowired
    private PropertyService propertyService;

    public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    public Map<String, Object> getQqUserInfo(LoginParam loginParam) {
//        Map<String, Object> map =  getOpenid(code);

//        String accessToken = (String)map.get("accessToken");
//        String openId = (String)map.get("openid");

        String strUrl = "https://graph.qq.com/user/get_user_info";
        String method = "GET";

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", loginParam.getAccess_token());
        params.put("openid", loginParam.getOpenid());
        params.put("oauth_consumer_key", propertyService.getV("qq_login_appid"));

        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();
            /**
             * 返回数据格式
             * 文档：https://wiki.open.qq.com/wiki/%E3%80%90QQ%E7%99%BB%E5%BD%95%E3%80%91%E5%BC%80%E5%8F%91%E6%94%BB%E7%95%A5_Server-side#Step5.EF.BC.9A.E4.BD.BF.E7.94.A8Access_Token.E4.BB.A5.E5.8F.8AOpenID.E6.9D.A5.E8.AE.BF.E9.97.AE.E5.92.8C.E4.BF.AE.E6.94.B9.E7.94.A8.E6.88.B7.E6.95.B0.E6.8D.AE
             * {
             *
             *    "ret":0,
             *    "msg":"",
             *    "nickname":"YOUR_NICK_NAME",
             *    ...
             * }
             *
             */
            Map<String, Object> userInfo = (Map<String, Object>) JSON.parse(rs);
            if(!userInfo.containsKey("ret") || (int)userInfo.get("ret") != 0) {
                logger.error("invoke qq api error");
                throw new RRException("调用qq接口失败");
            }
            userInfo.put("openid", loginParam.getOpenid());
            return userInfo;
        } catch (IOException e) {
            logger.error("invoke qq api error", e);
            throw new RRException("调用qq接口失败");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }


    /**
     * 根据code获取token
     * @param code
     * @return token和openid
     *
     * @throws Exception
     */
    public Map<String, Object> getOpenid(String code){
        String strUrl = "https://graph.qq.com/oauth2.0/me";
        String method = "GET";
        Map<String, Object> map =  new HashMap<>();

        String accessToken = getAccessToken(code);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("access_token", accessToken);

        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();

            String openId = StringUtils.substringBetween(rs, "\"openid\":\"", "\"}");
            if(StringUtils.isEmpty(openId)) {
                logger.error("invoke qq api error");
                throw new RRException("调用qq接口失败，openid为空");
            }
            map.put("openid", openId);
            map.put("accessToken", accessToken);
            return map;
        } catch (IOException e) {
            logger.error("invoke qq api error", e);
            throw new RRException("调用qq接口失败");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }


    /**
     * 根据code获取token
     * @param code
     * @return token
     *
     * @throws Exception
     */
    public String getAccessToken(String code){
        String strUrl = "https://graph.qq.com/oauth2.0/token";
        String method = "GET";

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("grant_type", "authorization_code");
        params.put("client_id", propertyService.getV("qq_login_appid"));
        params.put("client_secret", propertyService.getV("qq_login_secret"));
        params.put("code", code);
        params.put("redirect_uri", propertyService.getV("qq_login_redirect_uri"));

        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            StringBuffer sb = new StringBuffer();
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sb.append(strRead);
            }
            rs = sb.toString();

            System.out.println("rs:"+rs);
            String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(rs, "&");

            String accessToken = StringUtils.substringAfterLast(items[0], "=");
            if(StringUtils.isEmpty(accessToken)) {
                logger.error("invoke qq api error");
                throw new RRException("调用qq接口失败，access_token为空");
            }

            return accessToken;
        } catch (IOException e) {
            logger.error("invoke qq api error", e);
            throw new RRException("调用qq接口失败");
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    public static String urlencode(Map<String,Object>data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
